<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
  <base href="/oa1/" /> <!-- 与现有页面base路径保持一致 -->
  <title>襄阳蓝芯智能化办公系统 - 客户关心产品</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 加载现有页面相同的CSS资源 -->
  <link href="static/bootstrap-3.3.5/css/bootstrap.css" rel="stylesheet">
  <link href="static/bootstrapvalidator/css/bootstrapValidator.css" rel="stylesheet">
  <!-- 自定义表头样式（与现有一致） -->
  <style>
    .thead-blue {
      color: #fff;
      font-weight: bold;
      background-color: #337ab7;
    }
    .form-group { margin-bottom: 15px; } /* 保持表单间距一致 */
    .modal-footer { margin-top: 0; }    /* 模态框底部间距统一 */
  </style>
  <!-- 加载现有页面相同的JS资源 -->
  <script src="static/jquery/jquery-1.10.2.min.js"></script>
  <script src="static/bootstrap-3.3.5/js/bootstrap.min.js"></script>
  <script src="static/bootstrapvalidator/js/bootstrapValidator.js"></script>
</head>
<body>

<!-- 1. 提示信息模态框（页面加载时若有错误，自动弹出） -->
<div class="modal fade" id="alertMsgModal" tabindex="-1" role="dialog" aria-labelledby="alertMsgModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xs"> <!-- 与现有模态框尺寸一致 -->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="alertMsgModalLabel">提示</h4>
      </div>
      <div class="modal-body" id="alertmsg">
        <c:if test="${param.alertMsg == 'repeat'}">该产品已在客户关心列表中，无需重复添加！</c:if>
        <c:if test="${param.alertMsg == 'paramError'}">参数不完整，请填写所有必填项！</c:if>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>


<!-- 2. 添加客户关心产品表单面板（与现有搜索面板风格一致） -->
<div class="panel panel-primary">
  <div class="panel-heading">
    <h4 class="panel-title">[admin] 客户关心产品管理</h4> <!-- 标题风格与现有一致 -->
  </div>
  <div class="panel-body">
    <!-- 添加表单：form-horizontal 布局，与现有表单结构一致 -->
    <form action="favorite/editKhCustomerfavorite" id="addFavoriteForm" method="post" class="form-horizontal" role="form">
      <!-- 隐藏字段：传递当前客户ID -->
      <input type="hidden" name="customerid" value="${customerid}">

      <div class="form-group col-md-12">
        <!-- 产品名称下拉框 -->
        <label for="productid" class="col-md-1 control-label">产品名称</label>
        <div class="col-md-3">
          <select id="productid" name="productid" class="form-control">
            <option value="">--请选择产品--</option>
            <c:forEach items="${products}" var="product">
              <option value="${product.oid}">${product.linkname}</option>
            </c:forEach>
          </select>
        </div>

        <!-- 客户意向下拉框 -->
        <label for="status" class="col-md-1 control-label">客户意向</label>
        <div class="col-md-3">
          <select id="status" name="status" class="form-control">
            <option value="">--请选择意向--</option>
            <option value="1">有意向</option>
            <option value="2">已签订合同</option>
            <option value="3">已付款</option>
            <option value="4">已发货</option>
            <option value="5">无效</option>
          </select>
        </div>

        <!-- 操作按钮：风格与现有一致（btn-success/btn-info） -->
        <div class="col-md-3">
          <button type="submit" class="btn btn-success">添加客户关心</button>
          <button type="button" onclick="location.href='kh/customer/listKhCustomer'" class="btn btn-info">返回客户列表</button>
        </div>
      </div>
    </form>
  </div>
</div>


<!-- 3. 客户关心产品列表（与现有客户列表风格一致） -->
<div class="panel panel-primary">
  <table class="table table-bordered table-hover"> <!-- 表格样式统一 -->
    <thead>
    <tr class="thead-blue" align="center"> <!-- 表头样式：thead-blue -->
      <td>产品编号</td>
      <td>产品名称</td>
      <td>产品规格</td>
      <td>客户意向</td>
      <td>客户跟踪</td>
      <td>操作</td>
    </tr>
    </thead>
    <tbody>
    <!-- 遍历分页数据：无数据时显示提示 -->
    <c:if test="${pageResult.total == 0}">
      <tr align="center">
        <td colspan="6">暂无客户关心产品数据</td>
      </tr>
    </c:if>

    <c:forEach items="${pageResult.records}" var="favorite">
      <tr align="center">
        <td>${favorite.productid}</td>
        <td>${favorite.productName}</td>
        <td>${favorite.productInfo == null ? '--' : favorite.productInfo}</td>
        <!-- 客户意向文字回显（编码转文字） -->
        <td>
          <c:choose>
            <c:when test="${favorite.status == 1}">有意向</c:when>
            <c:when test="${favorite.status == 2}">已签订合同</c:when>
            <c:when test="${favorite.status == 3}">已付款</c:when>
            <c:when test="${favorite.status == 4}">已发货</c:when>
            <c:when test="${favorite.status == 5}">无效</c:when>
            <c:otherwise>未知状态</c:otherwise>
          </c:choose>
        </td>
        <!-- 客户跟踪操作：按钮风格与现有一致（btn-success/btn-info btn-xs） -->
        <td>
          <button onclick="openAddContactModal(${favorite.oid}, '${favorite.productName}')"
                  class="btn btn-success btn-xs" type="button">客户跟踪</button>
          <a href="favorite/listKhContactrecord?favoriteid=${favorite.oid}&customerid=${customerid}"
             class="btn btn-info btn-xs">跟踪记录</a>
        </td>
        <!-- 修改/删除操作：按钮风格统一（btn-primary/btn-danger btn-xs） -->
        <td>
          <button onclick="openUpdateModal(${favorite.oid}, ${favorite.customerid}, ${favorite.productid}, ${favorite.status}, '${favorite.productName}')"
                  class="btn btn-primary btn-xs" type="button">修改意向</button>
          <button onclick="setDeleteOid(${favorite.oid}, ${favorite.customerid})"
                  class="btn btn-danger btn-xs" data-toggle="modal" data-target="#confirmDeleteModal">删除</button>
        </td>
      </tr>
    </c:forEach>
    </tbody>
  </table>
</div>


<!-- 4. 分页控件（与现有分页风格完全一致） -->
<div class="input-group col-md-6 col-md-offset-3">
  <div class="row">
    <div class="btn-group">
      <!-- 首页 -->
      <button onclick="gotoPage(1, ${pageResult.size})" class="btn btn-primary" type="button">首页</button>
      <!-- 上一页：当前页=1时禁用 -->
      <button onclick="gotoPage(${pageResult.current - 1}, ${pageResult.size})"
              class="btn btn-primary ${pageResult.current == 1 ? 'disabled' : ''}" type="button">上一页</button>
      <!-- 当前页/总页数 -->
      <button class="btn btn-primary disabled" type="button">当前第${pageResult.current}/${pageResult.pages}页</button>
      <!-- 每页条数下拉 -->
      <div class="btn-group">
        <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          每页显示${pageResult.size}条 <span class="caret"></span>
        </button>
        <ul class="dropdown-menu">
          <li><a href="javascript:gotoPage(1,5)">每页显示5条</a></li>
          <li><a href="javascript:gotoPage(1,10)">每页显示10条</a></li>
          <li><a href="javascript:gotoPage(1,15)">每页显示15条</a></li>
          <li><a href="javascript:gotoPage(1,20)">每页显示20条</a></li>
        </ul>
      </div>
      <!-- 总记录数 -->
      <button class="btn btn-primary disabled" type="button">共${pageResult.total}条记录</button>
      <!-- 下一页：当前页=总页数时禁用 -->
      <button onclick="gotoPage(${pageResult.current + 1}, ${pageResult.size})"
              class="btn btn-primary ${pageResult.current == pageResult.pages ? 'disabled' : ''}" type="button">下一页</button>
      <!-- 尾页 -->
      <button onclick="gotoPage(${pageResult.pages}, ${pageResult.size})"
              class="btn btn-primary ${pageResult.current == pageResult.pages ? 'disabled' : ''}" type="button">尾页</button>
    </div>
  </div>
</div>


<!-- 5. 分页表单（隐藏，用于页码/条数提交） -->
<form action="favorite/listKhCustomerfavorite" id="pageForm" method="post" class="form-horizontal" role="form">
  <input type="hidden" name="customerid" value="${customerid}">
  <input type="hidden" name="page" id="pageNum" value="${pageResult.current}">
  <input type="hidden" name="pageSize" id="pageSize" value="${pageResult.size}">
</form>


<!-- 6. 修改客户意向模态框（与现有模态框风格一致） -->
<div class="modal fade" id="updateStatusModal" tabindex="-1" role="dialog" aria-labelledby="updateStatusLabel" aria-hidden="true">
  <div class="modal-dialog modal-xs"> <!-- 小尺寸模态框 -->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="updateStatusLabel">修改客户意向</h4>
      </div>
      <!-- 修改表单：与添加表单结构一致 -->
      <form action="favorite/editKhCustomerfavorite" id="updateStatusForm" method="post" class="form-horizontal" role="form">
        <div class="modal-body">
          <!-- 隐藏字段：传递主键oid、客户ID、产品ID -->
          <input type="hidden" name="oid" id="updateOid">
          <input type="hidden" name="customerid" id="updateCustomerid">
          <input type="hidden" name="productid" id="updateProductid">

          <!-- 产品名称回显（禁用） -->
          <div class="form-group row">
            <label class="col-md-4 control-label">产品名称</label>
            <div class="col-md-6">
              <input type="text" id="updateProductName" class="form-control" disabled>
            </div>
          </div>

          <!-- 客户意向下拉（可修改） -->
          <div class="form-group row">
            <label class="col-md-4 control-label">客户意向</label>
            <div class="col-md-6">
              <select id="updateStatus" name="status" class="form-control">
                <option value="1">有意向</option>
                <option value="2">已签订合同</option>
                <option value="3">已付款</option>
                <option value="4">已发货</option>
                <option value="5">无效</option>
              </select>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
          <button type="submit" class="btn btn-primary">确认修改</button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- 7. 客户跟踪模态框（风格统一） -->
<div class="modal fade" id="addContactModal" tabindex="-1" role="dialog" aria-labelledby="addContactLabel" aria-hidden="true">
  <div class="modal-dialog modal-xs">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="addContactLabel">添加客户跟踪记录</h4>
      </div>
      <!-- 跟踪表单：验证规则与现有一致 -->
      <form action="favorite/addKhContactrecord" id="addContactForm" method="post" class="form-horizontal" role="form">
        <div class="modal-body">
          <!-- 隐藏字段：关联的客户-产品ID -->
          <input type="hidden" name="favoriteid" id="contactFavoriteid">

          <!-- 产品名称回显（禁用） -->
          <div class="form-group row">
            <label class="col-md-3 control-label">产品名称</label>
            <div class="col-md-8">
              <input type="text" id="contactProductName" class="form-control" disabled>
            </div>
          </div>

          <!-- 客户联系人下拉（加载当前客户的联系人） -->
          <div class="form-group row">
            <label class="col-md-3 control-label">客户联系人</label>
            <div class="col-md-8">
              <select id="contactEmpid" name="empid" class="form-control">
                <option value="">--请选择联系人--</option>
                <c:forEach items="${contacts}" var="contact">
                  <option value="${contact.oid}">${contact.contactName}</option>
                </c:forEach>
              </select>
            </div>
          </div>

          <!-- 事由输入框 -->
          <div class="form-group row">
            <label class="col-md-3 control-label">事由</label>
            <div class="col-md-8">
              <input type="text" name="reason" id="contactReason" class="form-control" placeholder="请输入跟踪事由">
            </div>
          </div>

          <!-- 联系结果文本域 -->
          <div class="form-group row">
            <label class="col-md-3 control-label">联系结果</label>
            <div class="col-md-8">
              <textarea name="result" id="contactResult" class="form-control" rows="5" placeholder="请输入详细联系结果"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="reset" class="btn btn-default" data-dismiss="modal">关闭</button>
          <button type="submit" class="btn btn-primary">确认添加</button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- 8. 删除确认模态框（与现有删除模态框一致） -->
<div class="modal fade" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="confirmDeleteLabel">提示</h4>
      </div>
      <div class="modal-body">确认删除该客户关心的产品吗？</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" id="confirmDeleteBtn" class="btn btn-primary">提交删除</button>
      </div>
    </div>
  </div>
</div>


<!-- 9. 核心JS逻辑（表单验证、模态框交互、分页、删除） -->
<script type="text/javascript">
  // 全局变量：存储删除所需的oid和customerid
  var deleteOid = null;
  var deleteCustomerid = null;

  // 页面加载完成后初始化
  $(document).ready(function() {
    // 1. 初始化所有表单验证
    myformValidator();   // 添加客户关心产品表单验证
    initAddContactFormValid();    // 客户跟踪表单验证
    initUpdateStatusFormValid();  // 修改意向表单验证

    // 2. 若有提示参数，自动弹出提示模态框
    <c:if test="${not empty param.alertMsg}">
    $('#alertMsgModal').modal('show');
    </c:if>

    // 3. 删除确认按钮绑定事件
    $("#confirmDeleteBtn").click(function() {
      doDelete();
      $('#confirmDeleteModal').modal('hide');
    });

    // 4. AJAX错误统一处理（与现有一致）
    $(document).ajaxError(function(event, xhr) {
      if(xhr.status == "403"){
        document.location.href = xhr.getResponseHeader("url");
      }else if(xhr.status != "200"){
        console.log("服务器错误!");
        $("#alertmsg").text("服务器错误，请稍后重试！");
        $('#alertMsgModal').modal('show');
      }
    });
  });


  // -------------------------- 分页功能（与现有一致） --------------------------
  function gotoPage(page, pageSize) {
    $("#pageNum").val(page);
    $("#pageSize").val(pageSize);
    $("#pageForm").submit();
  }


  // -------------------------- 添加客户关心产品表单验证 --------------------------
  function myformValidator(){
    $("#addFavoriteForm").bootstrapValidator({
      message : 'This value is not valid',
      feedbackIcons : {
        valid : 'glyphicon glyphicon-ok',
        invalid : 'glyphicon glyphicon-remove',
        validating : 'glyphicon glyphicon-refresh'
      },
      fields : {
        productid : {
          validators : {
            notEmpty : {
              message : '请选择关心的产品'
            },
            remote:{
              url:"favorite/checkKhCustomerfavorite",
              delay:1000,
              type:'post',  // 确保请求类型为POST
              message:'当前产品已在客户关心列表!',
              data:function(validator){
                return {
                  // 确保正确获取customerid的值
                  'customerid': $("input[name='customerid']").val(),
                  'productid': $("#productid").val()
                };
              }
            }
          }
        },
        status: { // 客户意向：非空
          validators: {
            notEmpty: { message: "请选择客户意向" }
          }
        }
      },
      submitHandler: function(validator, form, submitButton) {
        validator.defaultSubmit(); // 验证通过后提交表单
      }
    });
  }


  // -------------------------- 修改客户意向模态框交互 --------------------------
  // 打开修改模态框（回显数据）
  function openUpdateModal(oid, customerid, productid, status, productName) {
    $("#updateOid").val(oid);
    $("#updateCustomerid").val(customerid);
    $("#updateProductid").val(productid);
    $("#updateStatus").val(status); // 回显当前意向
    $("#updateProductName").val(productName); // 回显产品名称
    $("#updateStatusModal").modal('show'); // 显示模态框
  }

  // 修改意向表单验证
  function initUpdateStatusFormValid() {
    $("#updateStatusForm").bootstrapValidator({
      message: "输入值无效",
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        status: { // 仅验证意向非空（其他字段为隐藏/禁用）
          validators: {
            notEmpty: { message: "请选择客户意向" }
          }
        }
      },
      submitHandler: function(validator, form, submitButton) {
        validator.defaultSubmit();
      }
    });
  }


  // -------------------------- 客户跟踪模态框交互 --------------------------
  // 打开跟踪模态框（回显产品名称）
  function openAddContactModal(favoriteid, productName) {
    $("#contactFavoriteid").val(favoriteid);
    $("#contactProductName").val(productName);
    $("#addContactModal").modal('show');
  }

  // 客户跟踪表单验证
  function initAddContactFormValid() {
    $("#addContactForm").bootstrapValidator({
      message: "输入值无效",
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        empid: { // 联系人：非空
          validators: {
            notEmpty: { message: "请选择客户联系人" }
          }
        },
        reason: { // 事由：非空
          validators: {
            notEmpty: { message: "请填写跟踪事由" }
          }
        },
        result: { // 结果：非空
          validators: {
            notEmpty: { message: "请填写联系结果" }
          }
        }
      },
      submitHandler: function(validator, form, submitButton) {
        validator.defaultSubmit();
      }
    });

    // 模态框关闭后重置表单和验证（避免残留旧数据）
    $('#addContactModal').on('hidden.bs.modal', function() {
      $("#addContactForm").data('bootstrapValidator').destroy();
      $('#addContactForm').data('bootstrapValidator', null);
      initAddContactFormValid(); // 重新初始化验证
      $("#addContactForm")[0].reset(); // 清空表单
    });
  }


  // -------------------------- 删除功能 --------------------------
  // 设置要删除的oid和customerid
  function setDeleteOid(oid, customerid) {
    deleteOid = oid;
    deleteCustomerid = customerid;
  }

  // 执行删除（AJAX请求后端）
  function doDelete() {
    $.get("favorite/deleteKhCustomerfavorite", { "oid": deleteOid }, function(result) {
      if (result) { // 删除成功：刷新页面
        location.href = "favorite/listKhCustomerfavorite?customerid=" + deleteCustomerid;
      } else { // 删除失败：提示有跟踪记录
        $("#alertmsg").text("删除失败！该产品有关联的客户跟踪记录，无法删除。");
        $('#alertMsgModal').modal('show');
      }
    });
  }
</script>
</body>
</html>